/**
 * MdiTab
 * @type class
 * @since 1.0 <2015-9-17> SoChishun <14507247@qq.com> Added.
 * @since 1.1 <2015-10-7> SoChishun 新增选项卡数量限制功能.
 * @since 1.2 <2015-10-10> SoChishun 新增Cookie缓存功能,刷新页面的时候会自动还原打开过的选项卡,新增fn_add_tab_by_menu_id()和fn_before_init()
 * @since 1.3 <2015-10-12> SoChishun 新增Cookie移除功能;新增打开到已有选项卡功能;新增刷新选项卡功能
 * @since 1.4 <2015-10-15> SoChishun 新增loading效果,新增fn_iframe_load()和fn_iframe_loaded()
 */
var MdiTab = {
    newInstance: function () {
        /**
         * 类对象
         * @type object
         */
        var obj = {
            tabCounter: 1,
            /**
             * 配置
             */
            config: {
                tab_id: '#tab_main',
                cookie_name: 'mditabck',
                limit: 10,
                refresh_on_active: false,
            },
            /**
             * 设置配置
             * @param JSON options
             * @since 1.0 <2015-9-17> SoChishun Added.
             */
            setConfig: function (options) {
                $.extend(this.config, options);
            },
            /**
             * 根据菜单编号添加选项卡的委托方法
             * @since 1.0 <2015-10-10> SoChishun Added.
             */
            fn_add_tab_by_menu_id: function (ids) {
                // 示例代码
                var $a;
                var $menu = $('.menu-nav');
                for (var i in ids) {
                    $a = $menu.find('a[data-id="' + ids[i] + '"]');
                    if ($a[0]) {
                        this.add_tab({title: $a.text(), url: $a.attr('href'), menu_id: ids[i]});
                    }
                }
            },
            /**
             * 初始化前置事件委托方法
             * @since 1.0 <2015-10-10> SoChishun Added.
             */
            fn_before_init: function () {
            },
            /**
             * iframe加载前事件委托方法
             * @since 1.0 <2015-10-15> SoChishun Added.
             */
            fn_iframe_load: function ($iframe) {
                if ($iframe[0]) {
                    $iframe.contents().find('body').html('<span style="font-size:12px; color:#999;">正在加载页面,请稍后...</span>');
                }
                //$(document.body).append('<div id="doc-loading" style="position:absolute;left:45%;width:200px;height:36px;top:45%;background:#FFFFFF;opacity:0.8;filter:alpha(opacity=60);z-index:9999999;"><div style="border:2px solid #B7CDFC;cursor:pointer;margin:0 auto;width:200px;height:36px;line-height:36px;font-size:12px;background:#fff;text-align:center;position:relative;">加载中,请稍后...<a href="#" onclick="$(this).parent().parent().remove();return false;" style="position:absolute;right:2px;top:2px;text-decoration:none;color:#666;">&times</a></div></div>');
            },
            /**
             * iframe加载成功事件委托方法
             * @since 1.0 <2015-10-15> SoChishun Added.
             */
            fn_iframe_loaded: function (ifrm) {
                //$('#doc-loading').remove();
                $(ifrm).height(this.get_window_height());
            },
            /**
             * 初始化
             * @since 1.0 <2015-9-10> SoChishun Added.
             */
            init: function () {
                this.fn_before_init();
                var tabs = $(this.config.tab_id).tabs();
                // 关闭选项卡
                tabs.delegate("span.ui-icon-close", "click", function () {
                    var panelId = $(this).closest("li").remove().attr("aria-controls");
                    $("#" + panelId).remove();
                    if (obj.config.cookie_name) {
                        obj.remove_history(panelId.substring(5)); // 从历史菜单移除
                    }
                    tabs.tabs("refresh");
                });
                tabs.bind("keyup", function (event) {
                    if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
                        var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
                        $("#" + panelId).remove();
                        tabs.tabs("refresh");
                    }
                });
                // 激活后再点击,刷新选项卡
                tabs.delegate(".ui-tabs-nav li", "click", function () {
                    var $li = $(this);
                    if (obj.config.refresh_on_active || $li.data('isActived')) {
                        var panelId = $(this).closest("li").attr("aria-controls");
                        var src = $("#" + panelId).find('iframe').attr('src');
                        if (src) {
                            obj.fn_iframe_load($("#" + panelId).find('iframe'));
                            $("#" + panelId).find('iframe').attr('src', 'about:blank').attr('src', src);
                            tabs.tabs("refresh");
                        }
                        return;
                    }
                    $li.data('isActived', true).attr('title', '再次点击则刷新.').siblings().data('isActived', false).attr('title', '');
                });
                this.load_history();
            },
            /**
             * 添加导航标签
             * @param JSON options 参数选项
             * @returns int 返回当前选项卡的编号
             * @since 1.0 <2015-9-10> SoChishun Added.
             * @since 1.1 <2015-10-10> SoChishun 新增返回当前选项卡的编号
             * @since 1.2 <2015-10-12> SoChishun 参数改为options,新增通过menu_id比对的功能
             * @example add_tab({title:$(this).text(), url:$(this).attr('href')});
             */
            add_tab: function (options) {
                var config = {
                    title: '', // [string] 标题
                    url: '', // [string] 链接地址
                    mutex: true, // [bool] 是否独占菜单模式(相同的菜单只能打开一个,重复点击菜单会激活已有菜单)
                    menu_id: '', // [int] 菜单编号
                    refresh_on_active: false, // 重复激活的时候自动刷新
                    add_history: true, // 是否添加到历史记录
                };
                $.extend(config, options);
                var $cur = $(this.config.tab_id + '>ul').find(config.menu_id ? ('a[href="#tabs-' + config.menu_id + '"]') : ('a:contains("' + config.title + '")'));
                if ($cur[0] && config.mutex) {
                    if (config.refresh_on_active) {
                        $cur.text(config.title);
                        $(this.config.tab_id).find('div[id="tabs-' + config.menu_id + '"]').find('iframe').attr('src', 'about:blank').attr('src', config.url);
                    }
                    var id = $cur.parent().parent().find('li').index($cur.parent());
                    $(this.config.tab_id).tabs({active: id});
                    return id;
                }
                var size = this.limit_tab();
                var tabs = $(this.config.tab_id).tabs();
                var tabTemplate = '<li><a href="#{href}">#{label}</a><span class="ui-icon ui-icon-close" role="presentation">x</span></li>';
                var label = config.title,
                        num = (config.menu_id ? config.menu_id : this.tabCounter),
                        id = "tabs-" + num,
                        li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label)),
                        tabContentHtml = '<iframe id="ifrm-' + num + '" frameborder="0" scrolling="yes" style="width:100%" src="about:blank" onload="mditab.fn_iframe_loaded(this)"></iframe>';
                tabs.find(".ui-tabs-nav").append(li);
                tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>");
                tabs.tabs("refresh");
                tabs.tabs({active: size});
                this.tabCounter++;

                // 优化iframe加载
                this.fn_iframe_load($('#ifrm-' + num));
                $('#ifrm-' + num).attr('src', config.url);

                // 添加到历史缓存
                if (config.add_history && config.menu_id) {
                    this.add_history(size, config.menu_id);
                }
                return size;
            },
            /**
             * 限制选项卡数量
             * @returns Number size 返回选项卡数量
             * @since 1.0 <2015-10-7> SoChishun Added.
             */
            limit_tab: function () {
                var $lis = $(this.config.tab_id + '>ul li');
                var size = $lis.size();
                if (this.config.limit > 0 && size >= this.config.limit) {
                    $lis.eq(0).remove();
                    size -= 1;
                }
                return size;
            },
            /**
             * 获取主容器高度
             * @returns Number
             * @since 1.0 2014-8-12 by sutroon
             */
            get_window_height: function (offset) {
                if (undefined == offset) {
                    offset = 170;
                }
                var winHeight = 0;
                if (window.innerHeight) {
                    winHeight = window.innerHeight;
                } else if ((document.body) && (document.body.clientHeight)) {
                    winHeight = document.body.clientHeight;
                }
                return winHeight - offset;
            },
            /**
             * 加载历史选项卡
             * @since 1.0 <2015-10-10> SoChishun Added.
             */
            load_history: function () {
                // 需要Cookies插件支持,请到https://github.com/js-cookie/js-cookie下载该插件
                if ('undefined' == typeof (Cookies)) {
                    return;
                }
                var str = Cookies.get(this.config.cookie_name);
                if (!str) {
                    return;
                }
                var idx = str.substring(0, str.indexOf(':'));
                var ids = str.substring(str.indexOf(':') + 1).split(',');
                this.fn_add_tab_by_menu_id(ids);
            },
            /**
             * 添加到历史缓存
             * @param int idx
             * @param int id
             * @since 1.0 <2015-10-10> SoChishun Added.
             */
            add_history: function (idx, id) {
                // 需要Cookies插件支持,请到https://github.com/js-cookie/js-cookie下载该插件
                if ('undefined' == typeof (Cookies)) {
                    return;
                }
                var str = Cookies.get(this.config.cookie_name);
                if (!str) {
                    str = idx + ':' + id;
                } else {
                    str = str.substring(str.indexOf(':') + 1);
                    if ((',' + str + ',').indexOf(',' + id + ',') < 0) {
                        str = str + ',' + id;
                    }
                    // 限制数量
                    if (this.config.limit > 0 && str.split(',').length >= this.config.limit) {
                        str = str.substring(str.indexOf(',') + 1);
                    }
                    str = idx + ':' + str;
                }
                Cookies.set(this.config.cookie_name, str);
            },
            /**
             * 从历史缓存移除
             * @param int id
             * @since 1.0 <2015-10-12> SoChishun Added.
             */
            remove_history: function (id) {
                if (!id || ('undefined' == typeof (Cookies))) {
                    return;
                }
                var str = Cookies.get(this.config.cookie_name);
                if (!str) {
                    return;
                }
                var idx = str.substring(0, str.indexOf(':'));
                str = str.substring(str.indexOf(':') + 1);
                var str2 = ',' + str + ',';
                if (str2.indexOf(',' + id + ',') < 0) {
                    return;
                }
                str = str2.replace(',' + id + ',', ',');
                str = str.substring(1, str.length - 1);
                str = idx + ':' + str;
                Cookies.set(this.config.cookie_name, str);
            }
        };
        return obj;
    }
}

